package com.cn.lf.wx.dacs.bussiness.author.action;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.cn.ym.log.Log;

public class Base {

    private static final Integer FIFTEEN_ID_CARD=15;
    private static final Integer EIGHTEEN_ID_CARD=18;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    
	public Map<String, Object> getmap(HttpServletRequest request) {
		Map<String, String[]> readOnlyMap = request.getParameterMap();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		for (String key : readOnlyMap.keySet()) {
			String value = readOnlyMap.get(key)[0];
			paramMap.put(key, value);
		}
		return paramMap;
	}
	public static String getResultFromConn(String req) throws IOException {
		String message = "";
		InputStream inputStream = null;
		HttpURLConnection connection = null;
		try {
			URL url = new URL(req);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(5*1000);
			inputStream = connection.getInputStream();
			InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
			char [] buff=new char[1024];
			int length=0;
			
			while((length=reader.read(buff))!=-1){
				message+=new String(buff,0,length);
			}
		/*	int size = inputStream.available();
			byte[] bs = new byte[size];
			inputStream.read(bs);
			message = new String(bs, "UTF-8");
			System.out.println(message);*/
			connection.disconnect();
			return message;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(connection != null) {
				connection.disconnect();
			}
		}
		return message;
	}
	
	public static List<Map<String,Object>> getJsonList(String jsonarray){
		JSONArray jsonarr=JSONArray.fromObject(jsonarray);
		 List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		for(int i=0;i<jsonarr.size();i++){
			JSONObject json=(JSONObject) jsonarr.get(i);
			Map<String,Object> tempMap=JsonToMap(json);
			list.add(tempMap);
		}
		return list;
	}
	   /**
     * 获取postJson数据
     * @param request
     * @return
     */
	public Map<String,Object> getJsonMap(HttpServletRequest request){
		  Map<String,Object> map=null;
		try {
			InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8");
			char [] buff=new char[1024];
			int length=0;
			String requestjson="";
			while((length=reader.read(buff))!=-1){
				requestjson+=new String(buff,0,length);
			}
			JSONObject json = JSONObject.fromObject(requestjson);
			 map=JsonToMap(json);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			Log.error(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.error(e.getMessage());
		}
		return map;
	}
	public static Map<String,Object> JsonToMap(JSONObject j){
	    Map<String,Object> map = new HashMap<>();
	    Iterator<String> iterator = j.keys();
	    while(iterator.hasNext())
	    {
	        String key = (String)iterator.next();
	        Object value = j.get(key);
	        map.put(key, value);
	    }
	    return map;
	}
	public static String getResultFromConnUrlPost(String urls,String data) throws IOException {
		String message = null;
		InputStream inputStream = null;
		HttpURLConnection connection = null;
		  DataOutputStream dos=null;
		try {
		
			URL url = new URL(urls);
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(5*1000);
		
			connection.setDoOutput(true);     
			connection.setDoInput(true);      
			connection.setUseCaches(false);   
			connection.setRequestMethod("POST");
			 //设置请求属性
			connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			connection.setRequestProperty("Charset", "UTF-8");
		
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.connect();
		    //建立输入流，向指向的URL传入参数
		     dos=new DataOutputStream(connection.getOutputStream());
		    dos.writeBytes(data);
		    dos.flush();
		    dos.close();
			
			inputStream = connection.getInputStream();
			int size = inputStream.available();
			byte[] bs = new byte[size];
			inputStream.read(bs);
			message = new String(bs, "UTF-8");
			connection.disconnect();
			return message;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(connection != null) {
				connection.disconnect();
			}
			if(dos!=null){
				 dos.close();
			}
		}
		return message;
	}
	public static String getResultFromConnJsonPost(String req,String data) throws IOException {
		String message = null;
		InputStream inputStream = null;
		HttpURLConnection connection = null;
		  DataOutputStream dos=null;
		try {
			URL url = new URL(req);
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(5*1000);
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);     
			connection.setDoInput(true);      
			connection.setUseCaches(false);   
		
			 //设置请求属性
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("connection", "keep-alive");
			connection.connect();
			connection.getOutputStream().write(data.getBytes("UTF-8"));
			
			inputStream = connection.getInputStream();
			int size = inputStream.available();
			byte[] bs = new byte[size];
			inputStream.read(bs);
			message = new String(bs, "UTF-8");
			connection.disconnect();
			return message;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(connection != null) {
				connection.disconnect();
			}
			if(dos!=null){
				 dos.close();
			}
		}
		return message;
	}
	public static String getRequestJson(HttpServletRequest request){
		String requestjson="";
 		try {
			InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8");
				char [] buff=new char[1024];
				int length=0;
				
				while((length=reader.read(buff))!=-1){
					requestjson+=new String(buff,0,length);
				}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			return requestjson;
	}
	public String removefile(String filename, String data, HttpServletRequest request) throws IOException {
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMdd");
		String time = format.format(date);
		String ydpath = System.getProperty("user.dir") + "/src/main/webapp/static/temp/" + time + "/";// 上传到这个文件夹
		File file1 = new File(ydpath);
		if (!file1.exists()) {
			file1.mkdirs();
		}
		String serverName = request.getScheme() // 当前链接使用的协议
				+ "://" + request.getServerName()// 服务器地址
				+ ":" + request.getServerPort(); // 端口号
		String respath = ydpath + filename;

		FileWriter writer = new FileWriter(respath);
		writer.write(data);
		writer.flush();
		writer.close();
		String result = respath.replace(System.getProperty("user.dir") + "/src/main/webapp", serverName);
		return result;
	}

	public static String generateBase64StringToFile(String fileStr, String filename, HttpServletRequest request) {
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMdd");
		String time = format.format(date);
		String ydpath = System.getProperty("user.dir") + "/src/main/webapp/static/temp/" + time + "/";// 上传到这个文件夹
		File file1 = new File(ydpath);
		if (!file1.exists()) {
			file1.mkdirs();
		}
		String serverName = request.getScheme() // 当前链接使用的协议
				+ "://" + request.getServerName()// 服务器地址
				+ ":" + request.getServerPort(); // 端口号
		String respath = ydpath + filename;
		if (fileStr == null) // 图像数据为空
			return null;
		try {
			// Base64解码
			byte[] b = Base64.decodeBase64(fileStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(respath);
			out.write(b);
			out.flush();
			out.close();
			String result = respath.replace(System.getProperty("user.dir") + "/src/main/webapp", serverName);

			return result;
		} catch (Exception e) {
			return null;
		}
	}
	//判断整数
	public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
	//字符串翻转
	public static String spiltRtoL(String s) {
		 
        StringBuffer sb = new StringBuffer();
        int length = s.length();
        char[] c = new char[length];
        for (int i = 0; i < length; i++) {
            c[i] = s.charAt(i);
        }
        for (int i = length - 1; i >= 0; i--) {
            sb.append(c[i]);
        }
 
        return sb.toString();
    }
	 /**
     * 根据身份证号获取性别
     * @param IDCard
     * @return
     */
    public static String getSex(String IDCard){
        String sex ="";
        if (StringUtils.isNotBlank(IDCard)){
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD){
                if (Integer.parseInt(IDCard.substring(14, 15)) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
                //18位身份证号
            }else if(IDCard.length() == EIGHTEEN_ID_CARD){
                // 判断性别
                if (Integer.parseInt(IDCard.substring(16).substring(0, 1)) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
            }
        }
        return sex;
    }

    /**
     * 根据身份证号获取年龄
     * @param IDCard
     * @return
     */
    public static Integer getAge(String IDCard){
        Integer age = 0;
        Date date = new Date();
        if (StringUtils.isNotBlank(IDCard)){
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD){
                // 身份证上的年份(15位身份证为1980年前的)
                String uyear = "19" + IDCard.substring(6, 8);
                // 身份证上的月份
                String uyue = IDCard.substring(8, 10);
                // 当前年份
                String fyear = format.format(date).substring(0, 4);
                // 当前月份
                String fyue = format.format(date).substring(5, 7);
                if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
                    // 当前用户还没过生
                } else {
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
                }
                //18位身份证号
            }else if(IDCard.length() == EIGHTEEN_ID_CARD){
                // 身份证上的年份
                String year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                String yue = IDCard.substring(10).substring(0, 2);
                // 当前年份
                String fyear = format.format(date).substring(0, 4);
                // 当前月份
                String fyue = format.format(date).substring(5, 7);
                // 当前月份大于用户出身的月份表示已过生日
                if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) {
                    age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
                    // 当前用户还没过生日
                } else {
                    age = Integer.parseInt(fyear) - Integer.parseInt(year);
                }
            }
        }
        return age;
    }

    /**
     * 获取出生日期  yyyy年MM月dd日
     * @param IDCard
     * @return
     */
    public static String getBirthday(String IDCard){
        String birthday="";
        String year="";
        String month="";
        String day="";
        if (StringUtils.isNotBlank(IDCard)){
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD){
                // 身份证上的年份(15位身份证为1980年前的)
               year = "19" + IDCard.substring(6, 8);
               //身份证上的月份
               month = IDCard.substring(8, 10);
                //身份证上的日期
               day= IDCard.substring(10, 12);
                //18位身份证号
            }else if(IDCard.length() == EIGHTEEN_ID_CARD){
                // 身份证上的年份
                year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                month = IDCard.substring(10).substring(0, 2);
                //身份证上的日期
                day=IDCard.substring(12).substring(0,2);
            }
            birthday=year+"-"+month+"-"+day;
        }
        return birthday;
    }
    public static Map<String,Object> getHeaderMap(HttpServletRequest request){
    	Map<String,Object> map=new HashMap<String, Object>();
    	Enumeration<?> enum1 = request.getHeaderNames();
        while (enum1.hasMoreElements()) {
            String key = (String) enum1.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
	
    public static void getBodyHeader(HttpServletRequest request,BufferedReader br){
    		 System.out.print(request.getHeaderNames());
        Enumeration<?> enum1 = request.getHeaderNames();
        while (enum1.hasMoreElements()) {
            String key = (String) enum1.nextElement();
            String value = request.getHeader(key);
            System.out.println(key + "\t" + value);
        }
        
      //body部分
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (Exception e) {
            System.out.println("IOException: " + e);
        }
        System.out.println("str:" + str);
        System.out.println("test");
    	
    }
	

}
